package com.liao.badminton.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.liao.badminton.code.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liao.badminton.code.myenum.GroupAdminEnum;
import com.liao.badminton.code.myenum.StipulationTypeEnum;
import com.liao.badminton.context.BaseContextHandler;
import com.liao.badminton.dto.ApplyJoinGroupDto;
import com.liao.badminton.dto.UserGroupRefDto;
import com.liao.badminton.entity.*;
import com.liao.badminton.mapper.JoinGroupApplyMapper;
import com.liao.badminton.mapper.UserGroupRefMapper;
import com.liao.badminton.redis.RedisEnum;
import com.liao.badminton.redis.RedisUtil;
import com.liao.badminton.code.util.EntityUtils;
import com.liao.badminton.code.util.CheckUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liao.badminton.service.BadmintonGroupService;
import com.liao.badminton.service.StipulationLevelService;
import com.liao.badminton.service.SystemUsersService;
import com.liao.badminton.service.UserGroupRefService;
import com.liao.badminton.vo.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Component;
import lombok.extern.log4j.Log4j2;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

import static cn.hutool.core.util.ObjectUtil.isEmpty;
import static cn.hutool.core.util.ObjectUtil.isNotEmpty;

/**
 * @author liaocheng
 * @date 2024-10-30
 * description:群表
 */
@Component
@Log4j2
public class UserGroupRefServiceImpl extends ServiceImpl<UserGroupRefMapper, UserGroupRef> implements UserGroupRefService {

    @Resource
    private BadmintonGroupService badmintonGroupService;
    @Resource
    private SystemUsersService systemUsersService;
    @Resource
    private StipulationLevelService stipulationLevelService;
    @Resource
    private JoinGroupApplyMapper joinGroupApplyMapper;

    /**
     * 新增
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, timeout = 10, rollbackFor = Exception.class)
    public ResponseRest<Long> saveUserGroupRef(UserGroupRefDto param) throws ProjectException {
        UserGroupRef userGroupRef = param.invertEntity();
        if (isEmpty(param.getCreateTime())) { //
            EntityUtils.setCreatAndUpdateInfo(param);
        } else {
            param.setCreator(BaseContextHandler.getCurrUserID());
        }
        EntityUtils.setCreatAndUpdateInfo(userGroupRef);
        this.save(userGroupRef);
        RedisUtil.toDelete(RedisEnum.CACHE_TABLE_DATA, "userGroupRef", "groupId", userGroupRef.getGroupId());
        return ResponseRest.suc("saveUserGroupRef", userGroupRef.getId());
    }

    /**
     * 删除
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, timeout = 10, rollbackFor = Exception.class)
    public ResponseRest<Boolean> deletesUserGroupRef(UserGroupRefDto param) throws ProjectException {
        boolean bool = this.removeByIds(param.getDelIds());
        if (bool) {
            param.getDelIds().forEach(id -> RedisUtil.toDelete(RedisEnum.CACHE_TABLE_DATA, "userGroupRef", "id", id));
        }
        return ResponseRest.suc("deletesUserGroupRef");
    }


    /**
     * 修改
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, timeout = 10, rollbackFor = Exception.class)
    public ResponseRest<Boolean> updateUserGroupRef(UserGroupRefDto param) throws ProjectException {
        UserGroupRef userGroupRef = param.invertEntity();
        EntityUtils.setUpdatedInfo(userGroupRef);
        boolean bool = this.updateById(userGroupRef);
        if (bool) {
            RedisUtil.toDelete(RedisEnum.CACHE_TABLE_DATA, "userGroupRef", "id", param.getId());
        }
        return ResponseRest.suc("updateUserGroupRef");
    }

    //查询时候用
    public void handlerStipulation(UserGroupRefVo userGroupRefVo) {
        if (isEmpty(userGroupRefVo)) {
            return;
        }
        Long groupId = userGroupRefVo.getGroupId();
        List<StipulationLevel> stipluationList = stipulationLevelService.list(new LambdaQueryWrapper<StipulationLevel>()
                .eq(StipulationLevel::getGroupId, groupId)
                .eq(StipulationLevel::getUseStatus, 1));
        if (CollectionUtil.isEmpty(stipluationList)) {
            return;
        }
        Long id = userGroupRefVo.getId();
        BigDecimal sourceNum = userGroupRefVo.getAwardCoin(); //用户值
        BigDecimal rankScore = userGroupRefVo.getAwardCoin(); //用户值
        BigDecimal winRate = new BigDecimal(userGroupRefVo.getWinBout() * 100).divide(new BigDecimal(userGroupRefVo.getTotalBout() == 0 ? 1 : userGroupRefVo.getTotalBout()), 2, BigDecimal.ROUND_HALF_UP);
        Integer stipulationType = stipluationList.get(0).getStipulationType();
//        List<BigDecimal> rankRateList = new ArrayList<>();
        Map<Integer, BigDecimal> rankScoreMap = new HashMap<>();
        List<KeyValue> rankRateByGroupId = new ArrayList<>();
        BigDecimal max = BigDecimal.ZERO; // <=
        BigDecimal min = BigDecimal.ZERO; // >=
        if (StipulationTypeEnum.RANK_NUM.getCode().equals(stipulationType)) {
            // 名次排序类型：1.胜率 2.获得奖励 3.净胜分
            rankRateByGroupId = (List<KeyValue>) RedisUtil.toGetDate(RedisEnum.CACHE_TABLE_DATA, "handlerStipulation", "groupId", groupId);
            Integer rankType = stipluationList.get(0).getRankType();
            //都是查排行的数字，没有对应的人，其中一个数值对应该多个人就不对了，比如100分的有10人，这10个有都是前5，99就不是前5了，
            // 应该把人数也查出来，或者所以人，按人排下来
            // 比如：a:100,b:100,c:100,d:100,e:100,f:100,g:100, //前5
            // h:93,i:92,j:91,k:90,l:89,m:88,n:87,o:86,p:85,q:84,r:84, //5-10
            // s:82,t:81,u:80,v:79,
            // w:78,x:77,y:76,z:75,aa:74,ab:73,
            // ac:71,ad:71,ae:70,af:69,ag:68,ah:67, //-5--10
            // ai:66,aj:65,ak:64,al:63,am:62,an:61,ao:60 //0--5
            if (StipulationTypeEnum.WIN_RATE.getCode().equals(rankType)) {
                rankScore = winRate;
                if (isEmpty(rankRateByGroupId)) {
                    rankRateByGroupId = baseMapper.findRankRateByGroupId(groupId);
                }
            } else if (StipulationTypeEnum.AWARD_NUM.getCode().equals(rankType)) {
                if (isEmpty(rankRateByGroupId))
                    rankRateByGroupId = baseMapper.findAwardCoinByGroupId(groupId);
            } else if (StipulationTypeEnum.RANK_NUM.getCode().equals(rankType)) {
                rankScore = new BigDecimal(userGroupRefVo.getTotalScore());
                if (isEmpty(rankRateByGroupId))
                    rankRateByGroupId = baseMapper.findTotalScoreByGroupId(groupId);
            }
            RedisUtil.toSaveRedis(RedisEnum.CACHE_TABLE_DATA, "handlerStipulation", "groupId", groupId, rankRateByGroupId, 2 * 60L);
            for (int i = 0; i < rankRateByGroupId.size(); i++) {
                KeyValue keyValue = rankRateByGroupId.get(i);

                for (StipulationLevel stipulationLevel : stipluationList) {
                    BigDecimal scopeLow = stipulationLevel.getScopeLow();//大于等于：   0  5  90   -5
                    BigDecimal scopeHigh = stipulationLevel.getScopeHigh();//小于：
                    if (scopeLow.compareTo(BigDecimal.ZERO) < 0) { //倒数排名 第5名  100+（-5） = 95  倒数第-5：-20
                        scopeHigh = new BigDecimal(rankRateByGroupId.size()).add( scopeHigh);// 0倒数第 100-0 = 100
                        scopeLow = new BigDecimal(rankRateByGroupId.size()).add( scopeLow).add(BigDecimal.ONE);// -5倒数第 100-5 95
                    }else{
                        if (scopeLow.compareTo(BigDecimal.ZERO) ==0) {
                            scopeLow = scopeLow.add(BigDecimal.ONE);
                        }
                    }
                    if (scopeLow.compareTo(BigDecimal.valueOf(i+1)) == 0) {
                        rankScoreMap.put(i+1, new BigDecimal(keyValue.getDataValue().toString()));
                    }
                    if (scopeHigh.compareTo(BigDecimal.valueOf(i+1)) == 0) {
                        rankScoreMap.put(i+1, new BigDecimal(keyValue.getDataValue().toString()));
                    }
                    if (max.compareTo(scopeHigh) < 0) {
                        max = scopeHigh;
                    }
                    if (min.compareTo(scopeLow) > 0) {
                        min = scopeLow;
                    }
                }
                if (keyValue.getDataKey().equals(id)) {
                    sourceNum = new BigDecimal(i + 1); // 第几位
                }

            }
        } else if (StipulationTypeEnum.WIN_RATE.getCode().equals(stipulationType)) {
            sourceNum = winRate;
        }
        if (!StipulationTypeEnum.RANK_NUM.getCode().equals(stipulationType)) {
            for (StipulationLevel stipulationLevel : stipluationList) {
                BigDecimal scopeLow = stipulationLevel.getScopeLow();//大于等于：   0  5  90   -5
                BigDecimal scopeHigh = stipulationLevel.getScopeHigh();//小于：
                if (max.compareTo(scopeHigh) < 0) {
                    max = scopeHigh;
                }
                if (min.compareTo(scopeLow) > 0) {
                    min = scopeLow;
                }
            }
        }
        //排名 -5的话
        for (StipulationLevel stipulationLevel : stipluationList) {
            BigDecimal scopeLow = stipulationLevel.getScopeLow();//大于等于：   0  5  90   -5
            BigDecimal scopeHigh = stipulationLevel.getScopeHigh();//小于：     5  20 100  -20
            if (scopeLow.compareTo(BigDecimal.ZERO) < 0) { //倒数排名
                scopeHigh = new BigDecimal(rankRateByGroupId.size()).add(scopeHigh);// 0倒数第100   251
                scopeLow = new BigDecimal(rankRateByGroupId.size()).add( scopeLow ).add(BigDecimal.ONE);//  -5倒数第95  246
            }else{
                if (scopeLow.compareTo(BigDecimal.ZERO) ==0) {
                    scopeLow = scopeLow.add(BigDecimal.ONE);
                }
            }


            if (StipulationTypeEnum.RANK_NUM.getCode().equals(stipulationType)) {
                BigDecimal bigDecimal = rankScoreMap.get(scopeLow.intValue());
                BigDecimal bigDecimal1 = rankScoreMap.get(scopeHigh.intValue());
                if (rankScore.compareTo(bigDecimal) == 0 || rankScore.compareTo(bigDecimal1) == 0) {
                    userGroupRefVo.setStipulationLevelId(stipulationLevel.getId());
                    userGroupRefVo.setLevelName(stipulationLevel.getLevelName());
                    userGroupRefVo.setEffect(stipulationLevel.getEffect());
                    break;
                }
                if ((sourceNum.compareTo(scopeLow) > 0 || min.compareTo(scopeLow) == 0)    //正数：前5 0<=x<=5  5<x<=20
                        && (sourceNum.compareTo(scopeHigh) <= 0 || max.compareTo(scopeHigh) == 0)) {
                    userGroupRefVo.setStipulationLevelId(stipulationLevel.getId());
                    userGroupRefVo.setLevelName(stipulationLevel.getLevelName());
                    userGroupRefVo.setEffect(stipulationLevel.getEffect());
                    break;
                }
            } else {
                if ((sourceNum.compareTo(scopeLow) >= 0 || min.compareTo(scopeLow) == 0) //正数：前5 90%<=x<=100%  80%<=x<90%
                        && (sourceNum.compareTo(scopeHigh) < 0 || max.compareTo(scopeHigh) == 0)) { //大于等于最低值，小于最高值
                    userGroupRefVo.setStipulationLevelId(stipulationLevel.getId());
                    userGroupRefVo.setLevelName(stipulationLevel.getLevelName());
                    userGroupRefVo.setEffect(stipulationLevel.getEffect());
                    break;
                }

            }
        }
    }


    /**
     * 查询列表
     */
    @Override
    public ResponseRest findUserGroupRefByPageParam(PageParam<UserGroupRefDto> pageParam) throws ProjectException {
        CheckUtil.checkValue(pageParam, "pageParam");
        UserGroupRefDto args = pageParam.getArgs();
        CheckUtil.checkValue(args, "pageParam.getArgs");
        if (ObjectUtil.isEmpty(args.getGroupId()) && ObjectUtil.isEmpty(args.getUserId()) && ObjectUtil.isEmpty(args.getId())) {
            args.setUserId(BaseContextHandler.getCurrUserID());
        }
//        CheckUtil.checkValue(pageParam.getArgs().getGroupId(), "群id不能为空");
        ResponseRest resp = ResponseRest.suc("findUserGroupRefByPageParam");
        PageHelper.startPage(pageParam.getCurrent(), pageParam.getSize());
        List<UserGroupRefVo> list = baseMapper.findByPageParam(pageParam);
        list.forEach(this::handlerStipulation);
        resp.setData(new PageInfo<>(list));
        return resp;
    }

    /**
     * 查询详情
     */
    @Override
    public ResponseRest findDetail(UserGroupRefDto param) throws ProjectException {
        Object getDate = RedisUtil.toGetDate(RedisEnum.CACHE_TABLE_DATA, "userGroupRef", "id", param.getId());
        if (isNotEmpty(getDate)) {
            RedisUtil.toFlushExpire(RedisEnum.CACHE_TABLE_DATA, "userGroupRef", "id", param.getId());
            return ResponseRest.suc("findDetail", (UserGroupRefVo) getDate);
        }
        UserGroupRefVo vo = null;
        UserGroupRef db = this.getById(param.getId());
        if (isNotEmpty(db)) {
            vo = UserGroupRefVo.invertToVo(db);
            handlerStipulation(vo);
            RedisUtil.toSaveRedis(RedisEnum.CACHE_TABLE_DATA, "userGroupRef", "id", param.getId(), vo, null);
        }
        return ResponseRest.suc("findDetail", vo);
    }

    /**
     * 查询详情
     */
    @Override
    public ResponseRest findOneCurrentIdGroupId(UserGroupRefDto param) throws ProjectException {

        UserGroupRefVo vo = null;
        UserGroupRef db = this.getOne(new LambdaQueryWrapper<UserGroupRef>().eq(UserGroupRef::getUserId, BaseContextHandler.getCurrUserID())
                .eq(UserGroupRef::getGroupId, param.getGroupId()));
        if (isNotEmpty(db)) {
            vo = UserGroupRefVo.invertToVo(db);
            RedisUtil.toSaveRedis(RedisEnum.CACHE_TABLE_DATA, "userGroupRef", "id", param.getId(), vo, null);
        }
        return ResponseRest.suc("findOneCurrentIdGroupId", vo);
    }

    @Override
    public UserGroupRef findUserGroupRefByGidUName(UserGroupRefDto param) throws ProjectException {
        LambdaQueryWrapper<UserGroupRef> eq = new LambdaQueryWrapper<UserGroupRef>()
                .eq(UserGroupRef::getGroupId, param.getGroupId())
                .eq(UserGroupRef::getUserName, param.getUserName());
        if (isNotEmpty(param.getSex())) {
            eq.eq(UserGroupRef::getSex, param.getSex());
        }
        List<UserGroupRef> userGroupRefs = baseMapper.selectList(eq);
        if (CollectionUtil.isEmpty(userGroupRefs)) {
            return null;
        }
        return userGroupRefs.get(0);
    }

    @Override
    public void updateByGroupIdAndUserName(UserGroupRefDto param) throws ProjectException {
        this.update(new LambdaUpdateWrapper<UserGroupRef>()
                .set(UserGroupRef::getUserId, param.getUserId())
                .eq(UserGroupRef::getGroupId, param.getGroupId())
                .eq(UserGroupRef::getUserName, param.getUserName()));
    }

    @Override
    public List<UserGroupRef> findByIds(List<Long> collect) {
        return this.listByIds(collect);
    }

    @Override
    public List<StatVo> findUserRankListByGroupId(Long groupId, Integer orderByType, Integer orderByTypeDesc, String teamOneName) {
        return baseMapper.findUserRankListByGroupId(groupId, orderByType, orderByTypeDesc,teamOneName);
    }

    @Override
    public ResponseRest<Boolean> setManager(UserGroupRefDto param) {
        CheckUtil.checkValue(param, "param");
        Long id = param.getId();
        Integer adminType = param.getAdminType();
        CheckUtil.checkValue(id, "主键id不能为空"); //以后可能传了userCode可以不传id，现在只能拉参数活动的人
        Long currUserID = BaseContextHandler.getCurrUserID();

        UserGroupRef userGroupRef = this.getById(id);
        if (userGroupRef.getAdminType() == GroupAdminEnum.owner.getCode()) {
            return ResponseRest.fail("setManager", "不能设置群主");
        }
        UserGroupRef currentUser = this.getOne(new LambdaQueryWrapper<UserGroupRef>()
                .eq(UserGroupRef::getUserId, currUserID)
                .eq(UserGroupRef::getGroupId, userGroupRef.getGroupId()));
        SystemUsers inviteUser;
        if (isNotEmpty(param.getUserCode())) {
            adminType = GroupAdminEnum.general.getCode(); //拉人成为普通成员
            inviteUser = systemUsersService.getOne(new LambdaQueryWrapper<SystemUsers>().eq(SystemUsers::getUserCode, param.getUserCode()));
            if (ObjectUtil.isEmpty(inviteUser)) {
                return ResponseRest.fail("setManager", "邀请用户不存在");
            }
            UserGroupRef inviteUserGroupRef = this.getOne(new LambdaQueryWrapper<UserGroupRef>().eq(UserGroupRef::getUserId, inviteUser.getId()).eq(UserGroupRef::getGroupId, userGroupRef.getGroupId()));
            if (isNotEmpty(inviteUserGroupRef) && !currUserID.equals(inviteUserGroupRef.getUserId())) { //不是切换自己，用户又已经存在
                return ResponseRest.fail("setManager", "该用户已经加入该群");
            }
            if (currUserID.equals(inviteUser.getId())) {
                baseMapper.updateOutUserBy(inviteUserGroupRef.getId()); //旧号置空
                adminType = GroupAdminEnum.owner.getCode();//设置新号为群主
            }
            param.setUserId(inviteUser.getId());
        }
        if (param.getDeleted() == null || param.getDeleted() == 0) {
            CheckUtil.checkValue(adminType, "设置类型不能为空");
        }
        if (userGroupRef == null) {
            return ResponseRest.fail("setManager", "用户不存在");
        }
        userGroupRef.setUserId(param.getUserId());
        if (param.getDeleted() != null && param.getDeleted() == -1) {
            baseMapper.updateOutUserBy(id); //退群
            return ResponseRest.suc("setManager", "退群成功");
        }
        if (param.getDeleted() != null && param.getDeleted() == -2) {
            baseMapper.deletes(CollectionUtil.newArrayList(id)); //物理删除
            return ResponseRest.suc("setManager", "删除记录成功");
        }

        if (ObjectUtil.isEmpty(currentUser) || currentUser.getAdminType() < 1) {
            return ResponseRest.fail("setManager", "群权限不足");
        }
        Integer currentUserAdminType = currentUser.getAdminType();
        if (adminType == GroupAdminEnum.admin.getCode() || adminType == GroupAdminEnum.owner.getCode()) { // 设置管理员
            if (!GroupAdminEnum.owner.getCode().equals(currentUserAdminType)) {
                return ResponseRest.fail("setManager", "非群主不能设置管理员");
            }
            if (adminType == GroupAdminEnum.owner.getCode()) { // 设置群主
                currentUser.setAdminType(GroupAdminEnum.general.getCode());
                EntityUtils.setUpdatedInfo(currentUser);
                currentUser.setUserId(null);
                this.updateById(currentUser);
            }
        }
        //不能将群主设成普通成员
        userGroupRef.setAdminType(adminType);
        EntityUtils.setUpdatedInfo(userGroupRef);
        this.updateById(userGroupRef);
        return ResponseRest.suc("setManager", "设置成功");
    }

    @Override
    public ResponseRest applyJoinGroup(ApplyJoinGroupDto param) {
        CheckUtil.checkValue(param, "param");
        CheckUtil.checkValue(param.getGroupCode(), "群分享码不能为空");
        String groupCode = param.getGroupCode();
        String userName = param.getUserName();
        BadmintonGroup one = badmintonGroupService.getOne(new LambdaQueryWrapper<BadmintonGroup>().eq(BadmintonGroup::getGroupCode, groupCode));
        if (ObjectUtil.isEmpty(one)) {
            return ResponseRest.fail("applyJoinGroup", "该群不存在");
        }
        Long groupId = one.getId();
        UserGroupRef hasDb = baseMapper.selectOne(new LambdaQueryWrapper<UserGroupRef>()
                .eq(UserGroupRef::getGroupId, groupId)
                .eq(UserGroupRef::getUserId, BaseContextHandler.getCurrUserID()));
        if (isNotEmpty(hasDb)) {
            return ResponseRest.fail("applyJoinGroup", "您已经加入该群");
        }
        Long userId = BaseContextHandler.getCurrUserID();
        if (isEmpty(userName)) {
            userName = BaseContextHandler.getUserName();
        }
        UserGroupRefDto userGroupRefDto = new UserGroupRefDto();
        userGroupRefDto.setGroupId(groupId);
        userGroupRefDto.setUserName(userName);
        userGroupRefDto.setSex(param.getSex());
        UserGroupRef userGroupRef = this.findUserGroupRefByGidUName(userGroupRefDto);
        if (isNotEmpty(userGroupRef) && userGroupRef.getUserId() != null) {
            return ResponseRest.fail("applyJoinGroup", userName + "：该名字和群已存在");
        }
        JoinGroupApply joinGroupApply = new JoinGroupApply();
        joinGroupApply.setGroupId(groupId);
        joinGroupApply.setNickname(userName);
        joinGroupApply.setUserId(userId);
        joinGroupApply.setSex(param.getSex());
        EntityUtils.setCreatAndUpdateInfo(joinGroupApply);
        joinGroupApplyMapper.add(joinGroupApply);
        if (one.getJoinType() == 1) { //自动加入，不需要审核
            ResponseRest responseRest = joinAppHandle(joinGroupApply.getId(), 1);
            if (responseRest.getSuc()) {
                return ResponseRest.suc("applyJoinGroup", "加入成功");
            } else {
                return responseRest;
            }
        }

        return ResponseRest.suc("applyJoinGroup", "申请成功,等待群管理员审核");
    }

    @Override
    public ResponseRest<PageInfo<JoinGroupApplyVo>> findApplyJoinGroupList(PageParam<JoinGroupApply> body) {
        CheckUtil.checkValue(body, "body");
        CheckUtil.checkValue(body.getArgs(), "body.getArgs");
        CheckUtil.checkValue(body.getArgs().getGroupId(), "群id不能为空");
        PageHelper.startPage(body.getCurrent(), body.getSize(), "create_time desc");
        List<JoinGroupApply> list = joinGroupApplyMapper.findByPageParam(body);
        List<JoinGroupApplyVo> collect = list.stream().parallel().map(entity -> JoinGroupApplyVo.invertToVo(entity)).collect(Collectors.toList());
        PageInfo<JoinGroupApplyVo> pageInfo = new PageInfo<>(collect);
        return ResponseRest.suc("findApplyJoinGroupList", pageInfo);
    }

    @Override
    public ResponseRest joinAppHandle(Long id, Integer status) {
        JoinGroupApply joinGroupApply = joinGroupApplyMapper.selectById(id);
        if (ObjectUtil.isEmpty(joinGroupApply)) {
            return ResponseRest.fail("joinAppHandle", "该申请不存在");
        }
        BadmintonGroup group = badmintonGroupService.getById(joinGroupApply.getGroupId());
        if (group.getJoinType() == 0) {
            Long currUserID = BaseContextHandler.getCurrUserID();    //当前用户id
            UserGroupRef userGroupRef1 = baseMapper.selectOne(new LambdaQueryWrapper<UserGroupRef>().eq(UserGroupRef::getUserId, currUserID).eq(UserGroupRef::getGroupId, joinGroupApply.getGroupId()));
            if (ObjectUtil.isEmpty(userGroupRef1) && status == 1) {
                return ResponseRest.fail("joinAppHandle", "您不在该群，不能处理该申请");
            }
            if (userGroupRef1.getAdminType() < 1) {
                return ResponseRest.fail("joinAppHandle", "您不是群管理员，不能处理该申请");
            }
        }
        if (status == 1) {
            UserGroupRefDto ugf = new UserGroupRefDto();
            ugf.setGroupId(joinGroupApply.getGroupId());
            ugf.setUserName(joinGroupApply.getNickname());
            ugf.setSex(joinGroupApply.getSex());
            UserGroupRef db = this.findUserGroupRefByGidUName(ugf);
            if (isNotEmpty(db)) {
                db.setUserId(joinGroupApply.getUserId());
                db.setAdminType(GroupAdminEnum.general.getCode());
                EntityUtils.setUpdatedInfo(db);
                this.updateById(db);
            } else {
                UserGroupRef userGroupRef = new UserGroupRef();
                userGroupRef.setGroupId(joinGroupApply.getGroupId());
                userGroupRef.setUserId(joinGroupApply.getUserId());
                userGroupRef.setUserName(joinGroupApply.getNickname());
                userGroupRef.setSex(joinGroupApply.getSex());
                userGroupRef.setAdminType(GroupAdminEnum.general.getCode());
                EntityUtils.setCreatAndUpdateInfo(userGroupRef);
                this.save(userGroupRef);
            }
            joinGroupApplyMapper.deleteById(id);
        } else if (status == 2)
            joinGroupApplyMapper.deleteById(id);
        return ResponseRest.suc("joinAppHandle", true);
    }


//    @Override
//    public void  handlerLoginRef(SystemUsersVo systemUsersVo,UserDetails jwtUser){
//        List<UserGroupRef> userGroupRefByUserId = this.list(new LambdaQueryWrapper<UserGroupRef>()
//                .eq(UserGroupRef::getUserId, systemUsersVo.getId()));
//        if (isNotEmpty(userGroupRefByUserId)) {
//            List<Long> groupIds = userGroupRefByUserId.stream().map(UserGroupRef::getGroupId).collect(Collectors.toList());
//            Map<Long,Integer> groupAdminMap = userGroupRefByUserId.stream().collect(Collectors.toMap(UserGroupRef::getGroupId, UserGroupRef::getAdminType));
//            UserGroupRef userGroupRef1 = userGroupRefByUserId.stream().filter(userGroupRef -> userGroupRef.getLoginDefault() == 1).findFirst().orElse(userGroupRefByUserId.get(0));
//            systemUsersVo.setDefaultGroupUserName(userGroupRef1.getUserName());
//            Long defaultGroupId = userGroupRef1.getGroupId();
//            if (userGroupRef1.getAdminType()>1) {
//                String[] array = new String[]{RoleCodeEnum.GROUP_ADMIN.getCode()};
//                jwtUser = User.withUsername(systemUsersVo.getUsername()).password((systemUsersVo.getPassword())).authorities(array).build();
//            }
//            systemUsersVo.setDefaultGroupId(defaultGroupId);
//            List<BadmintonGroup> badmintonGroups = badmintonGroupService.listByIds(groupIds);
//            for (BadmintonGroup badmintonGroup : badmintonGroups) {
//                if (badmintonGroup.getId().equals(defaultGroupId)) {
//                    systemUsersVo.setDefaultGroupName(badmintonGroup.getGroupName());
//                }
//                BadmintonGroupVo badmintonGroupVo = BadmintonGroupVo.invertToVo(badmintonGroup);
//                badmintonGroupVo.setAdminType(groupAdminMap.get(badmintonGroup.getId()));
//                systemUsersVo.getGroupList().add(badmintonGroupVo);
//
//            }
//        }
//    }

    @Override
    public ResponseRest<StatVo> allStat(Long groupId) {
        StatVo allStat = baseMapper.findAllStat(BaseContextHandler.getCurrUserID(), groupId);
        return ResponseRest.suc("allStat", allStat);
    }

    @Override
    public List<String> findUserNamesByGroupId(Long groupId) {

        return baseMapper.findUserNamesByGroupId(groupId);
    }

    @Override
    public void updateActivityNum(List ids, int updateNum) {
        baseMapper.updateActivityNum(ids, updateNum);
    }

    @Override
    public void updateCost(List<Long> userGId) {
        baseMapper.updateCost(userGId);
    }

}
